package com.ray.exception;

import cn.dev33.satoken.exception.*;
import com.ray.log.WebLogAspect;
import com.ray.util.Ret;
import io.lettuce.core.RedisCommandTimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @Value("spring.profiles.active")
    private String env;

    private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    // 拦截：未登录异常
    @ExceptionHandler(NotLoginException.class)
    public Ret handlerException(NotLoginException e) {
        return Ret.fail(401);
    }

    // 拦截：缺少权限异常
    @ExceptionHandler(NotPermissionException.class)
    public Ret handlerException(NotPermissionException e) {
        return Ret.fail(403).set("msg","缺少权限标识：" + e.getPermission());
    }

    // 拦截：缺少角色异常
    @ExceptionHandler(NotRoleException.class)
    public Ret handlerException(NotRoleException e) {
        return Ret.fail(403).set("msg","缺少角色权限：" + e.getRole());
    }

    // 拦截：二级认证校验失败异常
    @ExceptionHandler(NotSafeException.class)
    public Ret handlerException(NotSafeException e) {
        return Ret.fail("二级认证校验失败：" + e.getService());
    }

    // 拦截：服务封禁异常
    @ExceptionHandler(DisableServiceException.class)
    public Ret handlerException(DisableServiceException e) {
        return Ret.fail("当前账号 " + e.getService() + " 服务已被封禁 (level=" + e.getLevel() + ")：" + e.getDisableTime() + "秒后解封");
    }

    // 拦截：Http Basic 校验失败异常
    @ExceptionHandler(NotBasicAuthException.class)
    public Ret handlerException(NotBasicAuthException e) {
        return Ret.fail(e.getMessage());
    }

    // 拦截：没有资源异常
    @ExceptionHandler(NoResourceFoundException.class)
    public Ret handlerException(NoResourceFoundException e) {
        if("dev".equals(env))
            e.printStackTrace();
        return Ret.fail(404);
    }

    @ExceptionHandler(TransactionalException.class)
    public Ret handlerException(TransactionalException e) {
        if("dev".equals(env))
            e.printStackTrace();
        return Ret.fail(e.getMessage());
    }

    @ExceptionHandler(RedisCommandTimeoutException.class)
    public Ret handlerException(RedisCommandTimeoutException e) {
        if("dev".equals(env))
            e.printStackTrace();
        return Ret.fail("Redis服务器执行超时");
    }

    // 拦截：其它所有异常
    @ExceptionHandler(Exception.class)
    public Ret handlerException(Exception e) {
        if("dev".equals(env))
            e.printStackTrace();
        logger.error(e.getMessage());
        return Ret.fail("未知错误，请联系管理员！");
    }
}
